import store from '/@/store/index';

import { getModule, VuexModule, Module, Mutation, Action } from 'vuex-module-decorators';
import { toRaw } from 'vue';
import { userStore } from '/@/store/modules/user';
import { appStore } from '/@/store/modules/app';
import { PermissionModeEnum } from '/@/enums/appEnum';
import { filter } from '/@/utils/helper/treeHelper';
import { asyncRoutes } from '/@/router/routers/index';
const NAME = 'permission';
@Module({ dynamic: true, namespaced: true, store, name: NAME })
class Permission extends VuexModule {
  // 路由是否已经添加
  private isDynamicAddedRouteState = false;

  /**
   * @description: 路由是否已经添加
   */
  get getIsDynamicAddedRouteState() {
    return this.isDynamicAddedRouteState;
  }

  @Mutation
  commitDynamicAddedRouteState(status: boolean): void {
    this.isDynamicAddedRouteState = status;
  }

  @Action
  async buildRoutesAction(id?: number | string) {
    let routes = [];
    const roleList = toRaw(userStore.getRoleListState);

    const { permissionMode } = appStore.getProjectConfig;

    // 权限模式
    if (permissionMode === PermissionModeEnum.ROLE) {
      routes = filter(asyncRoutes, (route: any) => {
        const { meta } = route;
        const { roles } = meta || {};
        if (!roles) return true;
        return roleList.some((role) => roles.includes(role));
      });
    } else if (permissionMode === PermissionModeEnum.BACK) {
      // 动态路由  后台路由
      // TODO 后台路由待做
    }

    return routes;
  }
}

export const permissionStore = getModule(Permission);
